package com.bilibili.service.impl;

import com.alibaba.fastjson.JSON;
import com.bilibili.dto.CartoonCollectionCountDto;
import com.bilibili.entity.*;
import com.bilibili.exception.BusinessException;
import com.bilibili.mapper.PicCartoonMapper;
import com.bilibili.mapper.PicCollectionMapper;
import com.bilibili.mapper.UserMapper;
import com.bilibili.service.PicCollectionService;
import com.bilibili.utils.RedisOperations;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Tuple;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static com.bilibili.constant.BusinessConstant.*;

@Service
public class PicCollectionServiceImpl implements PicCollectionService {

    @Autowired
    private PicCollectionMapper picCollectionMapper;
    @Autowired
    private PicCartoonMapper picCartoonMapper;
    @Autowired
    private UserMapper userMapper;


    @Autowired
    private RedisOperations redisOperations;

    @Override
    public boolean selectCollectionByIds(User loginUser, Integer cartoonId) {
        PicCollection picCollection = picCollectionMapper.selectCollectionByIds(loginUser.getId(), cartoonId);
        return !Objects.isNull(picCollection);
    }


    @Override
    public boolean addCollection(User loginUser, Integer cartoonId) {
        //1.参数校验
        //判空
        if (Objects.isNull(loginUser)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "用户不能为空");
        }
        if (Objects.isNull(cartoonId)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画编号不能为空");
        }
        //涉及直接改变sql的代码
        PicCollection picCollection = new PicCollection();
        picCollection.setUserId(loginUser.getId());
        picCollection.setCartoonId(cartoonId);
        picCollectionMapper.addCollection(picCollection);

        //存在性
        PicCartoon cartoon = picCartoonMapper.getCartoonById(cartoonId);
        if (Objects.isNull(cartoon)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画编号不存在");
        } else {
            //对漫画收藏量+1
            redisOperations.zincrby(REDIS_CARTOON_COLLECTION_COUNT_KEY, COLLECTION_COUNT_INCREMENT + 0.0, String.valueOf(cartoonId));
//            //用户收藏漫画
//            //1.取出收藏的漫画
//            String collectionCIdsStr = redisOperations.hget(REDIS_USER_CARTOON_COLLECTION_KEY, loginUser.getId().toString());
//            if (!StringUtils.isBlank(collectionCIdsStr)) {
//                List<Integer> collectionCIds = JSON.parseArray(collectionCIdsStr, Integer.class);
//                collectionCIds.add(cartoonId);
//                redisOperations.hset(REDIS_USER_CARTOON_COLLECTION_KEY, loginUser.getId().toString(), JSON.toJSONString(Lists.newArrayList(cartoonId)));
//            } else {
//                redisOperations.hset(REDIS_USER_CARTOON_COLLECTION_KEY, loginUser.getId().toString(), JSON.toJSONString(Lists.newArrayList(cartoonId)));
//            }
//            //登录状态下添加商品的访问记录
////            if (!Objects.isNull(loginUser)) {
////                String historyKey = REDIS_USER_HISTORY_KEY_PREFIX + loginUser.getId();
////                String pidStr = String.valueOf(cartoonId);
////                //删除已经存在的相同的id
////                redisOperations.lrem(historyKey, REDIS_LREM_ALL_COUNT, pidStr);
////                //将访问过的idlpush进去
////                redisOperations.lpush(historyKey, pidStr);
////                //截断List长度到10为止
////                redisOperations.ltrim(historyKey, REDIS_HISTORTY_START_INDEX, HISTORY_PRODUCTS_SHOW_COUNT - 1);
////            }
        }
        return true;
    }

    @Override
    public boolean addPicCollection(User loginUser, Integer cartoonId) {
        //1.参数校验
        //判空
        if (Objects.isNull(loginUser)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "用户不能为空");
        }
        if (Objects.isNull(cartoonId)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画编号不能为空");
        }
        //存在性
        PicCartoon cartoon = picCartoonMapper.getCartoonById(cartoonId);
        if (Objects.isNull(cartoon)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画编号不存在");
        } else {
            //对漫画收藏量+1
            //用户收藏漫画
            redisOperations.lpush(PIC_USER_COLLECTION_CARTOON_KEY + loginUser.getId(), String.valueOf(cartoonId));
            //维持排行榜
            //1.取出收藏的漫画
            String collectionCIdsStr = redisOperations.hget(REDIS_USER_CARTOON_COLLECTION_KEY, String.valueOf(loginUser.getId()));
            if (!StringUtils.isBlank(collectionCIdsStr)) {
                //给他一个收藏量
                redisOperations.hset(REDIS_USER_CARTOON_COLLECTION_KEY, String.valueOf(loginUser.getId()), 1);
            } else {
                int originalValue = Integer.parseInt(collectionCIdsStr);
                redisOperations.hset(REDIS_USER_CARTOON_COLLECTION_KEY, String.valueOf(loginUser.getId()), originalValue + 1);
            }
//            redisOperations.
        }
        return true;
    }

    @Override
    public boolean delPicCollection(User loginUser, Integer cartoonId) {
        //1.参数校验
        //判空
        if (Objects.isNull(loginUser)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "用户不能为空");
        }
        if (Objects.isNull(cartoonId)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画编号不能为空");
        }
        //存在性
        PicCartoon cartoon = picCartoonMapper.getCartoonById(cartoonId);
        if (Objects.isNull(cartoon)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画编号不存在");
        } else {
            //对漫画收藏量+1
            //用户取消收藏漫画
            boolean lpop = redisOperations.lpop(PIC_USER_COLLECTION_CARTOON_KEY + loginUser.getId());
            if (!lpop) {
                throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画删除失败");
            }
            //维持排行榜
            //1.取出收藏的漫画
            String collectionCIdsStr = redisOperations.hget(REDIS_USER_CARTOON_COLLECTION_KEY, String.valueOf(loginUser.getId()));
            if (!StringUtils.isBlank(collectionCIdsStr)) {
                throw new BusinessException(HttpStatus.BAD_REQUEST, "没有人收藏过该漫画");
            } else {
                int originalValue = Integer.parseInt(collectionCIdsStr);
                redisOperations.hset(REDIS_USER_CARTOON_COLLECTION_KEY, String.valueOf(loginUser.getId()), originalValue - 1);
            }
        }
        return true;
    }


    @Override
    public List<CartoonCollectionCountDto> getPicCollectionRankList() {
        return picCartoonMapper.getCartoonCollectionRank();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public void syncRedisCollectionCountToMySql() {
        //1.从Redis中去读取所有的点击量数据
        long clickCountTupleCount = redisOperations.zcard(REDIS_CARTOON_COLLECTION_COUNT_KEY);
        Set<Tuple> redisClickCountTuple = redisOperations.zrevrangeWithScores(REDIS_CARTOON_COLLECTION_COUNT_KEY, REDIS_CARTOON_COLLECTION_START_OFFSET, clickCountTupleCount - 1);
        //2.从Redis中获取的点击量数据中得到所有商品的id和点击量
        List<CartoonCollectionCountDto> clickCountVos = new ArrayList<>();
        redisClickCountTuple.stream()
                .forEach(tuple -> {
                    String member = tuple.getElement();
                    int score = (int) tuple.getScore();
                    clickCountVos.add(new CartoonCollectionCountDto(Integer.parseInt(member), score));
                });
        //3.进行批量更新
        picCollectionMapper.batchUpdateClickCount(clickCountVos);
    }

    @Override
    public boolean delCollection(User loginUser, Integer cartoonId) {
        //1.参数校验
        //判空
        if (Objects.isNull(loginUser)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "用户不能为空");
        }
        if (Objects.isNull(cartoonId)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画编号不能为空");
        }
        //涉及直接改变sql的代码
        picCollectionMapper.delCollect(loginUser.getId(),cartoonId);

        //存在性
        PicCartoon cartoon = picCartoonMapper.getCartoonById(cartoonId);
        if (Objects.isNull(cartoon)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画编号不存在");
        } else {
            //对漫画收藏量-1
            redisOperations.zincrby(REDIS_CARTOON_COLLECTION_COUNT_KEY, COLLECTION_COUNT_DECREASE + 0.0, String.valueOf(cartoonId));
            //用户收藏漫画
            //1.取出收藏的漫画
//            String collectionCIdsStr = redisOperations.hget(REDIS_USER_CARTOON_COLLECTION_KEY, loginUser.getId().toString());
//            if (!StringUtils.isBlank(collectionCIdsStr)) {
//                List<Integer> collectionCIds = JSON.parseArray(collectionCIdsStr, Integer.class);
//                collectionCIds.add(cartoonId);
//                redisOperations.hset(REDIS_USER_CARTOON_COLLECTION_KEY, loginUser.getId().toString(), JSON.toJSONString(Lists.newArrayList(cartoonId)));
//            } else {
//                redisOperations.hset(REDIS_USER_CARTOON_COLLECTION_KEY, loginUser.getId().toString(), JSON.toJSONString(Lists.newArrayList(cartoonId)));
//            }
        }
        return true;
    }

//    @Override
//    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
//    public void syncRedisCollectionCountToMySql() {
//        //先保存排行榜
//        redisOperations.hgetall()
//        List<Integer> userIdList = userMapper.getAllUserId();
//
//    }


}
